//
//  ECScriptApi.m
//  ECDevelopKit
//
//  Created by LittoCats on 8/8/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "ECSScriptApi.h"
#import "ECSUtilities.h"

#import <objc/message.h>

#if TARGET_OS_IPHONE


@implementation ECSScriptApi : NSObject 

+ (id)dispatchApi:(NSString *)api argumnts:(NSArray *)arguments action:(NSMutableDictionary *)action completionHandler:(void (^)(id arg))handler
{
    Class domain = [self analyseDomain:action[@"api"]];
    SEL selector = [self analyseApi:api];
    
    NSAssert([domain respondsToSelector:selector], @"[ECSScriptApi] error , api < %@ > for domain < %@ > not exist .", api, action[@"__domain"]);
    
    NSMethodSignature *sig = [domain methodSignatureForSelector:selector];
    if ([domain respondsToSelector:@selector(analyseAction:)])
        objc_msgSend(domain, @selector(analyseAction:), action);
    
    id result;
    const char *returnType = [sig methodReturnType];
    if (returnType[0] == _C_VOID)
        objc_msgSend(domain, selector, arguments, action, handler);
    else if (returnType[0] == _C_ID)
        result = objc_msgSend(domain, selector, arguments, action, handler);
    else
        @throw [[NSException alloc] initWithName:@"ECSScriptApi" reason:@"api 返回值类型只能为 id" userInfo:nil];
    
    return result ? result : NSNull.null;
}

+ (Class)analyseDomain:(NSString *)domainName
{
    static NSMutableDictionary *domainTable = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        domainTable = [NSMutableDictionary new];
    });
    
    Class domain = [domainTable objectForKey:domainName ? domainName : @"master"];
    if (!domain) {
        NSString *domainStr = [[NSString alloc] initWithFormat:@"ECSScriptApi%@%@",domainName && domainName.length ? @"_" : @"" ,domainName ? domainName : @""];
        domain = NSClassFromString(domainStr);
        NSAssert(domain, @"[ECSScriptApi] error , api domain for < %@ > not exist.",domainName ? domainName : @"master");
        [domainTable setObject:domain forKey:domainName ? domainName : @"master"];
    }
    return domain;
}

+ (SEL)analyseApi:(NSString *)apiName
{
    return NSSelectorFromString([apiName stringByAppendingString:@":action:completionHandler:"]);
}

//*******************************ECSScriptApi***********************************//
+ (void)ECS_Script_API(timer)
{
    
}

@end

#endif

#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || TARGET_OS_WIN32
#endif